#include "air001xx_hal.h"
#include "led.h"
#include "usart.h"
#include "api_timer.h"
#include "button.h"
static void SystemClock_Config(uint32_t HSICLKSource_SET);

int main(void)
{
	HAL_Init();
	SystemClock_Config(RCC_HSICALIBRATION_24MHz); // 通过倍频器（PLL）固定的2倍频，得到48MHz
	MX_TIM14_Init();
	MX_GPIO_Init();
	MX_USART1_UART_Init();
	uint8_t Sysclock = HAL_RCC_GetSysClockFreq() / 1000000;
	while (1)
	{
		led_blink();
		//printf("Sysclock:%d MHz\n", Sysclock);
		KEY_SEVER();
	}
}

void Error_Handler(void)
{
	while (1)
	{
	}
}

/**
 * @brief   配置系统时钟
 * @param   HSICLKSource_SET：选择HSI时钟频率
 *            @arg @ref RCC_HSICALIBRATION_8MHz：8M时钟
 *            @arg @ref RCC_HSICALIBRATION_16MHz：16M时钟
 *            @arg @ref RCC_HSICALIBRATION_22p12MHz：22.12M时钟
 *            @arg @ref RCC_HSICALIBRATION_24MHz：24M时钟
 * @retval  无
 */
static void SystemClock_Config(uint32_t HSICLKSource_SET)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI; /* 配置HSE、HSI、LSI、LSE */
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;											/* 开启内部高速时钟HSI */
	// RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; /* HSI不分频 HSIDIV*/
	RCC_OscInitStruct.HSICalibrationValue = HSICLKSource_SET; /* HSI校准频率8MHz */
	// RCC_OscInitStruct.HSEState = RCC_HSE_OFF;			/* 关闭HSE */
	// RCC_OscInitStruct.HSEFreq = RCC_HSE_16_32MHz;		/* HSE频率范围16~32MHz */
	// RCC_OscInitStruct.LSIState = RCC_LSI_ON;				/*开启内部低速时钟 关闭LSI:RCC_LSI_OFF */
	/* RCC_OscInitStruct.LSEDriver = RCC_LSEDRIVE_MEDIUM; */ /* 默认LSE驱动能力 */

	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; /* 开启PLL 关闭PLL:RCC_PLL_OFF*/
	// RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; // RCC_PLLSOURCE_HSI   RCC_PLLSOURCE_NONE
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; /* PLL内部时钟源 RCC_PLLSOURCE_NONE*/

	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
	{
		Error_Handler();
	}

	/* 配置振荡器 */
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
	{
		Error_Handler();
	}

	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; /* 配置SYSCLK、HCLK、PCLK */
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;									   /* 配置系统时钟为HSI RCC_SYSCLKSOURCE_PLLCLK RCC_SYSCLKSOURCE_HSI*/
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;											   /* AHB时钟不分频 */
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;											   /* APB时钟不分频 */
	/* 配置时钟源 */
	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) // 48MHz LATENCY=1
	{
		Error_Handler();
	}
}
